<template>
  <div class="article-wrapper">
    <el-form
      label-position="top"
      label-width="80px"
      :model="formModel"
      ref="formInsRef"
      :rules="rules"
    >
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="文章标题" prop="title">
            <el-input
              v-model="formModel.title"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文章类别" prop="category">
            <SelectDict :queryValue="['CATEGORY']" v-model="formModel.category" placeholder="请输入" multiple clearable filterable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文章标签" prop="tag">
            <SelectDict :queryValue="['TAG']" v-model="formModel.tag" placeholder="请输入" multiple clearable filterable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="简介" prop="desc">
            <el-input
              v-model="formModel.desc"
              maxlength="300"
              placeholder="请输入"
              show-word-limit
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="缩略图" prop="picture">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :auto-upload="true"
              :http-request="httpRequestHandler"
            >
              <el-image v-if="formModel.picture" :src="formModel.picture" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <MdEditor
      v-model="formModel.markdown"
      @change="onChange"
      :sanitize="setSanitize"
      @uploadImg="onUploadImg"
      :theme="theme"
    />
  </div>
  <BottomButton :confirm="onSubmit" />
</template>

<script lang="js" setup>
import { setModel, delayFn, filterEmptyAttrByObj, formatJSON } from "@/utils"
import { ref, reactive, onMounted, inject, computed } from "vue"
import { articleUpsertApi, articleAddApi, articleDetailApi } from "@/api/article"
import { ElMessage } from "element-plus"
import { MdEditor } from "md-editor-v3"
import "md-editor-v3/lib/style.css"
import { originUpload } from '@/utils/qiniu';
import { useRoute, useRouter } from "vue-router"

const isDark = inject('isDark', ref('light'));
const theme = computed(() => isDark.value === 'dark' ? 'dark' : 'light');

const router = useRouter()
const route = useRoute()

const emits = defineEmits(["success"])
const formInsRef = ref()
const formModel = reactive({
  id: "",
  title: "",
  desc: "",
  html: "",
  markdown: "",
  category: undefined,
  tag: undefined,
  picture: "",
})

const onChange = v => {
  // text.value = v formModel.markdown
}
const setSanitize = html => {
  formModel.html = html
  return html
}
const onUploadImg = async (files, callback = () => {}) => {
  console.log('onUploadImg', files);
    const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          originUpload(file)
          .then((res) => rev(res))
          .catch((error) => rej(error));
        });
      })
    );
    callback(res?.filter((item) => item?.url));
  };

const httpRequestHandler = async (file) => {
  const res = await originUpload(file?.file)
  formModel.picture = res?.url
}
  
const rules = reactive({
  title: [{ required: true, message: "请输入" }],
})

const handleClose = () => {
  // done?.()
  formInsRef.value?.resetFields()
}

const buildParams = (params = {}) => {
  const postParams = {
    ...params,
    ...formModel,
  }
  return filterEmptyAttrByObj(postParams)
}

const submitHandler = async () => {
  const params = buildParams()
  if (params?.id) {
    await articleUpsertApi(params)
  } else {
    await articleAddApi(params)
  }
  ElMessage.success("操作成功")
}

const onClose = () => {}

const onSubmit = () => {
  if (!formInsRef.value) return
  formInsRef.value.validate(async valid => {
    if (valid) {
      console.log("submit!")
      await submitHandler()
      handleClose()
      emits("success")
      await delayFn()
      router.back()
    } else {
      console.log("error submit!")
    }
  })
}

const init = async () => {
  const id = route.params?.id;
  if (id) {
    const row = await articleDetailApi(id);
    const res = {
      ...row,
      tag: formatJSON(row?.tag),
      category: formatJSON(row?.category),
    }
    Object.assign(formModel, setModel(formModel, res))
  }
}

onMounted(() => {
  init()
})

</script>


<style lang="less" scoped>
  .article-wrapper {
    height: 100%;
    overflow: auto;
    padding-bottom: 48px;
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      &:hover {
        border-color: #06B880;
      }
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 96px;
      height: 96px;
      text-align: center;
    }
    .avatar {
      width: 96px;
      height: 96px;
      display: block;
    }
  }
</style>
